<!--
 * @Author: JohnYang
 * @Date: 2020-09-23 14:41:53
 * @LastEditors: Zhang Yingying
 * @LastEditTime: 2020-11-23 22:31:45
-->
<template>
  <div class="view">
    <h1>{{ title }}中规车</h1>
    <el-form
      ref="form"
      :rules="rules"
      label-width="140px"
      :model="model"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
    >
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item prop="brand" label="品牌：">
            <form-control
              @change="handleBrandChange"
              v-model="model.brand"
              placeholder="请选择品牌"
              :options="brands"
              :disabled="readonly"
              type="select"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="vehicleModel" label="车型：">
            <form-control
              v-model="model.vehicleModel"
              placeholder="请选择车型"
              :options="CarSubOptions"
              type="select"
              :disabled="readonly"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="region" label="区域：">
            <form-control
              v-model="model.region"
              placeholder="请选择区域"
              :options="regions"
              type="select"
              :disabled="readonly"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="dealerName" label="车行：">
            <form-control
              :readonly="readonly"
              v-model="model.dealerName"
              placeholder="请填写车行"
              type="input"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="billAmount" label="发票金额：">
            <form-control
              :readonly="readonly"
              v-model.number="model.billAmount"
              type="input"
              placeholder="请填写发票金额"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="milesUsed" label="购买时公里数：">
            <form-control
              :readonly="readonly"
              v-model.number="model.milesUsed"
              type="input"
              placeholder="请填写购买时公里数"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="vehicleProperty" label="车辆属性：">
            <form-control
              v-model="model.vehicleProperty"
              placeholder="请选择车辆属性"
              type="select"
              :disabled="readonly"
              :options="vehicleProperties"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="frameNum" label="车架号：">
            <form-control
              :readonly="readonly"
              v-model.trim="model.frameNum"
              placeholder="请填写车架号"
              type="input"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="engineNum" label="发动机号：">
            <form-control
              v-model.trim="model.engineNum"
              type="input"
              :readonly="readonly"
              placeholder="请填写发动机号"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="gearBoxNum" label="变速箱号：">
            <form-control
              v-model="model.gearBoxNum"
              placeholder="请选择变速箱号"
              type="select"
              :disabled="readonly"
              :options="gearBoxes"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="vipServiceFee" label="会员服务费：">
            <form-control
              :readonly="readonly"
              v-model.number="model.vipServiceFee"
              placeholder="请填写会员服务费"
              type="input"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="userName" label="会员姓名：">
            <form-control
              :readonly="readonly"
              v-model.trim="model.userName"
              placeholder="请填写会员姓名"
              type="input"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="telephone" label="联系电话：">
            <form-control
              v-model.trim="model.telephone"
              placeholder="请填写联系电话"
              type="input"
              :readonly="readonly"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="certificateType" label="证件类型：">
            <form-control
              v-model="model.certificateType"
              type="select"
              :disabled="readonly"
              :options="certificateTypes"
              placeholder="请填写证件类型"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="certificateNum" label="证件号码：">
            <form-control
              v-model.trim="model.certificateNum"
              type="input"
              :readonly="readonly"
              placeholder="请填写证件号码"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="address" label="地址：">
            <form-control
              v-model.trim="model.address"
              type="input"
              :readonly="readonly"
              placeholder="请填写地址"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="email" label="会员邮箱：">
            <form-control
              v-model.trim="model.email"
              type="input"
              :readonly="readonly"
              placeholder="请填写会员邮箱"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="qualityProtectTime" label="原车质保时间：">
            <form-control
              v-model="model.qualityProtectTime"
              type="select"
              :disabled="readonly"
              placeholder="请填写原车质保时间"
              :options="qualityProtectTimes"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="milesProtect" label="原车质保里程数：">
            <form-control
              v-model.number="model.milesProtect"
              type="input"
              :readonly="readonly"
              placeholder="请填写原车质保里程数"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="extendTime" label="延长时效：">
            <form-control
              v-model="model.extendTime"
              type="select"
              :disabled="readonly"
              :options="extendTimes"
              placeholder="请填写延长时效"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="calcMethod" label="结算方式：">
            <form-control
              v-model="model.calcMethod"
              type="select"
              :disabled="readonly"
              :options="calcMethods"
              placeholder="请填写结算方式"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="type !== 'normal'">
          <el-form-item prop="carNumber" label="车牌号:">
            <form-control
              v-model="model.carNumber"
              type="input"
              :disabled="readonly"
              placeholder="请填写车牌号"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="billDate" label="购车发票日期：">
            <form-control
              :readonly="readonly"
              :style="{ width: '100%' }"
              v-model="model.billDate"
              value-format="yyyy-MM-dd"
              placeholder="请选择购车发票日期"
              type="date"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="延保方案:" prop="extendPlan">
            <form-control
              v-model="model.extendPlan"
              type="select"
              :options="extendPlan1"
              :readonly="readonly"
              placeholder="请选择延保方案"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="comment" label="备注：">
            <form-control
              v-model.trim="model.comment"
              type="textarea"
              :readonly="readonly"
              :rows="3"
              placeholder="请填写备注"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="contractComment" label="合同备注：">
            <form-control
              v-model.trim="model.contractComment"
              type="textarea"
              :readonly="readonly"
              :rows="3"
              placeholder="请填写合同备注"
            ></form-control>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="影像资料：">
            <file-upload
              :disabled="readonly"
              @change="handleUploadChange"
              :type="type === 'normal' ? normalType : secondHandType"
              :file-list="model.imgs"
            ></file-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="mode == 'audit'">
          <el-form-item label="审批：">
            <el-radio-group v-model="state">
              <el-radio :label="passed">通过</el-radio>
              <el-radio :label="reject"> 不通过</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button
              v-if="mode != 'view' && mode != 'audit'"
              type="danger"
              :loading="saving"
              class="btn-normal"
              @click="handleSave"
            >
              保存
            </el-button>
            <el-button
              type="danger"
              v-if="mode == 'audit'"
              :loading="pending"
              class="btn-normal"
              @click="handleAudit"
              >审核</el-button
            >
            <el-button type="default" class="btn-normal" @click="handleBack">
              返回
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getCar, saveCar, auditCar } from "@/api";
import {
  validRequired,
  validMobilePhone,
  validEmail,
  normalType,
  secondHandType,
  passed,
  reject
} from "@/config";
import { StorageMixin } from "@/mixins/storage";
import FormControl from "@/components/FormControl.vue";
import FileUpload from "@/components/FileUpload.vue";
import { mapState } from "vuex";
export default {
  name: "IndexDetailView",
  mixins: [StorageMixin],
  components: {
    FormControl,
    FileUpload
  },
  data() {
    return {
      saving: false,
      loading: false,
      pending: false,
      normalType,
      secondHandType,
      passed,
      reject,
      type: "",
      mode: "",
      state: null,
      CarSubOptions: [],
      rules: {
        brand: [
          validRequired.registerError("请选择品牌").registerType("number")
        ],
        vehicleModel: [
          validRequired.registerError("请选择车型").registerType("number")
        ],
        region: [
          validRequired.registerError("请选择区域").registerType("number")
        ],
        dealerName: [validRequired.registerError("请填写车行")],
        billAmount: [
          validRequired.registerError("请填写发票金额").registerType("number")
        ],
        milesUsed: [
          validRequired
            .registerError("请填写购买时公里数")
            .registerType("number")
        ],
        vehicleProperty: [
          validRequired.registerError("请选择车辆属性").registerType("number")
        ],
        frameNum: [validRequired.registerError("请填写车架号")],
        engineNum: [validRequired.registerError("请填写发动机号")],
        gearBoxNum: [
          validRequired.registerError("请填写变速箱号").registerType("number")
        ],
        userName: [validRequired.registerError("请填写会员姓名")],
        telephone: [
          validRequired.registerError("请填写联系电话"),
          validMobilePhone.registerError("联系电话不正确")
        ],
        certificateType: [
          validRequired.registerError("请选择证件类型").registerType("number")
        ],
        vipServiceFee: [
          validRequired.registerError("请填写会员服务费").registerType("number")
        ],
        certificateNum: [validRequired.registerError("请填写证件号码")],
        address: [validRequired.registerError("请填写地址")],
        qualityProtectTime: [
          validRequired
            .registerError("请选择原车质保时间")
            .registerType("number")
        ],
        milesProtect: [
          validRequired
            .registerError("请填写原车质保里程数")
            .registerType("number")
        ],
        extendTime: [
          validRequired.registerError("请选择延长时效").registerType("number")
        ],
        calcMethod: [
          validRequired.registerError("请选择结算方式").registerType("number")
        ],
        carNumber: [validRequired.registerError("请填写车牌号")],
        billDate: [validRequired.registerError("请选择购车发票日期")],
        extendPlan: [
          validRequired.registerError("请选择延保方案").registerType("number")
        ]
      },
      temp: "",
      model: {
        id: null,
        brand: "",
        vehicleModel: "",
        billAmount: "",
        milesUsed: "",
        vehicleProperty: "",
        frameNum: "",
        engineNum: "",
        gearBoxNum: "",
        userName: "",
        telephone: "",
        certificateType: "",
        certificateNum: "",
        address: "",
        email: "",
        qualityProtectTime: "",
        milesProtect: "",
        extendTime: "",
        calcMethod: "",
        productRegion: "",
        singleLimit: "",
        totalLimit: "",
        carNumber: "",
        billDate: "",
        vipServiceFee: "",
        extendPlan: ""
      }
    };
  },
  computed: {
    ...mapState({
      admin: state => state.user.role
    }),
    title() {
      if (this.mode == "audit") {
        return "审核";
      } else if (this.mode == "view") {
        return "查看";
      } else {
        return this.model.id ? "编辑" : "新增";
      }
    },
    form() {
      return this.$refs.form;
    },
    readonly() {
      return this.admin == 1
        ? false
        : this.mode == "view" || this.mode == "audit";
    }
  },
  beforeRouteEnter(to, from, next) {
    next();
  },
  beforeRouteLeave(to, from, next) {
    if (this.form) {
      // this.form.resetFields();
      this.resetForm();
      this.form.clearValidate();
    }
    this.$nextTick(() => {
      next();
    });
  },
  mounted() {
    this.setParams();
  },
  methods: {
    resetForm() {
      Object.assign(this.model, {
        id: null,
        brand: "",
        vehicleModel: "",
        billAmount: "",
        milesUsed: "",
        vehicleProperty: "",
        frameNum: "",
        engineNum: "",
        gearBoxNum: "",
        userName: "",
        telephone: "",
        certificateType: "",
        certificateNum: "",
        address: "",
        email: "",
        qualityProtectTime: "",
        milesProtect: "",
        extendTime: "",
        calcMethod: "",
        productRegion: "",
        singleLimit: "",
        totalLimit: "",
        carNumber: "",
        billDate: "",
        vipServiceFee: "",
        extendPlan: ""
      });
    },
    handleUploadChange(data) {
      this.temp = data.join(",");
    },
    setParams() {
      let type = this.$route.query.type;
      let mode = this.$route.query.mode;
      this.type = type;
      this.mode = mode;
      let id = this.$route.query.id;
      this.model.id = id;
      if (!id) {
        return;
      }
      this.getDetail(id);
    },
    reshapeDetail(data) {
      return {
        ...data,
        gearBoxNum: Number.parseFloat(data.gearBoxNum),
        imgs: Array.isArray(data.imgs)
          ? data.imgs
              .filter(x => x !== "")
              .map((x, idx) => {
                return {
                  url: x,
                  name: "图片" + idx,
                  uid: idx
                };
              })
          : []
      };
    },
    async getDetail(id) {
      try {
        this.loading = true;
        let resp = await getCar(id, this.type);
        if (resp && resp.data) {
          Object.assign(this.model, this.reshapeDetail(resp.data));
          this.$nextTick(() => {
            this.handleBrandChange();
            this.model.vehicleModel = resp.data.vehicleModel;
          });
        } else {
          this.$interaction.showError("获取详细信息失败!");
        }
      } catch (exp) {
        console.error(exp);
      } finally {
        this.temp = "";
        this.loading = false;
      }
    },
    buildCar(car) {
      return { ...car, imgs: this.temp };
    },
    handleAudit() {
      if (this.state == null) {
        this.$interaction.showError("请选择审核状态!");
        return;
      }
      this.$interaction.showConfirm({
        message: "确定要审核当前的信息吗?",
        confirmed: async () => {
          this.pending = true;
          try {
            let resp = await auditCar({
              type: this.type == "normal" ? normalType : secondHandType,
              id: this.model.id,
              approve: this.state
            });
            if (resp && resp.code == 0) {
              this.$interaction.showSuccess("审核成功!");
              this.doBack();
            } else {
              this.$interaction.showError("审核失败!");
            }
          } catch (exp) {
            console.error(exp);
          } finally {
            this.pending = false;
          }
        }
      });
    },
    handleSave() {
      this.form &&
        this.form.validate(valid => {
          if (!valid) {
            return;
          }
          this.$interaction.showConfirm({
            message: "确定要保存当前编辑的信息吗?",
            confirmed: async () => {
              this.saving = true;
              try {
                let resp = await saveCar(
                  this.buildCar({ ...this.model, type: this.type })
                );
                if (resp && resp.code == 0) {
                  this.$interaction.showSuccess("保存成功!");
                  this.doBack();
                } else {
                  this.$interaction.showError("保存失败!");
                }
              } catch (exp) {
                console.error(exp);
              } finally {
                this.saving = false;
              }
            }
          });
        });
    },
    doBack() {
      this.temp = "";
      var routeName = this.type === "normal" ? "Index" : "SecondHand";
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        name: routeName,
        query: {
          type: this.type
        },
        replace: true
      });
    },
    handleBrandChange() {
      this.CarSubOptions = [];
      this.model.vehicleModel = "";
      let brand = this.model.brand;
      this.CarSubOptions = this.getCarsByBrand(brand);
    },
    handleBack() {
      if (this.mode == "view") {
        this.doBack();
      } else {
        this.$interaction.showConfirm({
          message: `确定要放弃${
            this.mode == "audit" ? "审核" : "编辑"
          }，并返回吗?`,
          confirmed: () => {
            this.doBack();
          }
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped></style>
